package com.canyou.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.canyou.service.RequestLogService;
import com.canyou.system.mapper.OperLogMapper;
import com.canyou.system.model.OperLog;
import com.canyou.system.service.OperLogService;
import com.canyou.utils.AddressUtils;
import com.canyou.utils.IpUtils;
import com.canyou.utils.JsonUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author canyou
 * @since 2019-05-14
 */
@Slf4j
@Service
public class OperLogServiceImpl extends ServiceImpl<OperLogMapper, OperLog>
        implements OperLogService, RequestLogService {

    @Autowired
    protected ObjectMapper objectMapper;

    @Async
    @Override
    public void insert(String module, String operation, String arg, Object result, Exception e,
                       HttpServletRequest request, Long times, String userName, String clientId) {
        try {
            //数据库日志
            OperLog operLog = new OperLog();
            operLog.setModule(module);
            operLog.setOperation(operation);
            operLog.setRequestUrl(request.getRequestURI());
            operLog.setRequestType(request.getMethod());
            operLog.setClientId(clientId);
            operLog.setSpendTime(times);
            operLog.setResponseCode(e == null ? 0 : 1);
            String ip = IpUtils.getIpAddr(request);
            operLog.setIpAddr(ip);
            operLog.setLocation(AddressUtils.getRealAddressByIp(ip));
            if (userName != null) {
                operLog.setUsername(userName);
            }
            if (e != null) {
                operLog.setResponseMsg(StrUtil.subWithLength(e.getMessage(), 0, 2000));
            }
            operLog.setRequestParam(arg);
            operLog.setResponseData(JsonUtils.toString(result));
            // 保存数据库
            baseMapper.insert(operLog);
        } catch (Exception exp) {
            log.error("异常信息:{}", exp.getMessage(), e);
        }
    }

    @Override
    public IPage<OperLog> getOperLogPage(IPage<OperLog> page, OperLog operLog) {
        return baseMapper.getOperLogPage(page, operLog);
    }

    @Override
    public List<OperLog> getOperLogList(OperLog operLog) {
        return baseMapper.getOperLogPage(operLog);
    }
}
